package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.igas.bean.CompareBean;
import cc.rengu.redp.bizimpl.igas.domain.PDstTxnAuthCfg;
import cc.rengu.redp.bizimpl.igas.service.PDstTxnAuthCfgService;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.FeeInfo;
import cc.rengu.redp.bizimpl.upmp.service.IBizTmpService;
import cc.rengu.redp.bizimpl.upmp.service.IFeeInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.FeeInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.ExcelDownload;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author 刘玉亮.LL
 */
@Api(tags = "商户管理:费率模板管理")
@Slf4j
@RestController
@RequestMapping(value = "/admin/fee/feeInfo")
public class FeeInfoController extends BaseController {
    private long oprMenuId = 1;
    private String oprMenuName = "商户管理:费率模板管理";
    private long chkMenuId = 2;
    private String chkMenuName = "商户管理:费率模板管理";
    private String webNextUrl = "/admin/fee/feeInfo/edit";
    @Autowired
    private IFeeInfoService feeInfoService;
    @Autowired
    private PDstTxnAuthCfgService pDstTxnAuthCfgService;

    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    
    //@RequiresPermissions("商户管理:费率模板管理")
    @GetMapping(value = "/list")
    @ApiOperation(value = "列表查询")
//    @RequiresPermissions("fee:view")
    public Map findByPage(QueryRequest request, FeeInfo entity) {
        return getDataTable(this.feeInfoService.findByPage(request, entity));
    }
    
    /**
     * 支付通道的费率管理
     * @param entity
     * @param model
     * @param request
     * @return
     */
    
    //@RequiresPermissions("产品管理:支付通道管理")
    @GetMapping(value = "/editFromChnl")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "id", value = "费率主键", required = false, dataType = "String")
    })
    public Map editFromChnl(@ModelAttribute("feeInfo") FeeInfo entity, Model model, HttpServletRequest request) throws RedpException {
        Map<String,Object> result= com.google.common.collect.Maps.newHashMap();
        List<FeeInfo> feeInfos;
        String optFlag = request.getParameter("optFlag");
        String instId= request.getParameter("instId");
        String dstChannelId = request.getParameter("dstChannelId");
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常！");
            }
            // 审核：获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getById(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据！");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }

            feeInfos = JSON.parseArray(bizdata, FeeInfo.class);

            if (Common.isBlank(feeInfos) || feeInfos.size() <= 0) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
            BeanUtils.copyProperties(feeInfos.get(0), entity);
        } else {
            // 新增，修改，注销，停用，启用，详情
            String feeCd = request.getParameter("feeCd");
            if(Common.isBlank(instId)){
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                instId = user.getInstId();
            }
            //如果请求参数中无feecd参数，则去取通道交易权限配置中的费率编码
            if(Common.isBlank(feeCd)){
                List<PDstTxnAuthCfg> list = pDstTxnAuthCfgService.findPDstTxnAuthCfgListByDstChannelId(instId,dstChannelId,null);
                if(CollectionUtils.isNotEmpty(list)){
                    PDstTxnAuthCfg pDstTxnAuthCfg = list.get(0);
                    feeCd = pDstTxnAuthCfg.getChannelTxnRate();
                }
            }

            feeInfos = feeInfoService.findcd(feeCd,instId);
            if (null != feeInfos && feeInfos.size() > 0) {
                BeanUtils.copyProperties(feeInfos.get(0), entity);
            }else {
                entity.setImpStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                entity.setStartDate(DateUtils.formatDate(new Date(), "yyyyMMdd"));
            }
        }
        result.put("entity", entity);
        result.put("feeinfos", feeInfos);
        result.put("optFlag", optFlag);
        result.put("dstChannelId", dstChannelId);
        return result;
    }

    /**
     * 支付通道交易的费率管理
     * @param entity
     * @param model
     * @param request
     * @return
     */
    
    //@RequiresPermissions("产品管理:支付通道管理")
    @GetMapping(value = "/editFromChnlTxn")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "channelTxn", value = "通道交易码", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "id", value = "费率主键", required = false, dataType = "String")
    })
    public FeeInfo editFromChnlTxn(@ModelAttribute("feeInfo") FeeInfo entity, Model model, HttpServletRequest request) throws RedpException {
        Map<String,Object> result= com.google.common.collect.Maps.newHashMap();
        List<FeeInfo> feeInfos;
        String optFlag = request.getParameter("optFlag");
        String instId= request.getParameter("instId");
        String dstChannelId=request.getParameter("dstChannelId");
        String channelTxn=request.getParameter("channelTxn");
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常！");
            }
            // 审核：获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getById(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据！");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }

            feeInfos = JSON.parseArray(bizdata, FeeInfo.class);

            if (Common.isBlank(feeInfos) || feeInfos.size() <= 0) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
            BeanUtils.copyProperties(feeInfos.get(0), entity);
        } else {
            // 新增，修改，注销，停用，启用，详情
            if(Common.isBlank(instId)){
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                instId = user.getInstId();
            }
            String feeCd="";
            if(StringUtils.isNotEmpty(channelTxn)){
                List<PDstTxnAuthCfg> list = pDstTxnAuthCfgService.findPDstTxnAuthCfgListByDstChannelId(instId,dstChannelId,channelTxn);
                if(CollectionUtils.isNotEmpty(list)){
                    PDstTxnAuthCfg pDstTxnAuthCfg = list.get(0);
                    feeCd = pDstTxnAuthCfg.getChannelTxnRate();
                }
            }

            feeInfos=new ArrayList<FeeInfo>();
            if(StringUtils.isNotEmpty(feeCd)){
                feeInfos = feeInfoService.findcd(feeCd,instId);
            }
            if (CollectionUtils.isNotEmpty(feeInfos)) {
                BeanUtils.copyProperties(feeInfos.get(0), entity);
            }else {
                entity.setImpStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                entity.setStartDate(DateUtils.formatDate(new Date(), "yyyyMMdd"));
            }
        }
        result.put("entity", entity);
        result.put("feeinfos", feeInfos);
        result.put("optFlag", optFlag);
        result.put("dstChannelId", dstChannelId);
        result.put("channelTxn", channelTxn);
        return entity;
    }

    
    //@RequiresPermissions("产品管理:支付通道管理")
    @PostMapping(value = "/editChannelTxnRate")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "dstChannelId", value = "通道标识", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "channelTxn", value = "通道交易码", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "feeCd", value = "费率代码", required = true, dataType = "String")
    })
    public OperationResult editChannelTxnRate(Model model, HttpServletRequest request) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String instId = request.getParameter("instId");
        String dstChannelId = request.getParameter("dstChannelId");
        String channelTxn = request.getParameter("channelTxn");
        String feeCd = request.getParameter("feeCd");
        String msgDstId = request.getParameter("msgDstId");
        PDstTxnAuthCfg pDstTxnAuthCfg = pDstTxnAuthCfgService.findOne(instId,msgDstId,channelTxn);
        if(pDstTxnAuthCfg!=null){
            pDstTxnAuthCfg.setChannelTxnRate(feeCd);
            pDstTxnAuthCfg.setUpdateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
            pDstTxnAuthCfgService.updatePDstTxnAuthCfg(pDstTxnAuthCfg);
        }

        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }

    private List<CompareBean> combare(FeeInfo tmpObj, FeeInfo formalObj){
        List<CompareBean> compareBeans = new ArrayList<>();
        if (!tmpObj.getFeeName().equals(formalObj.getFeeName())){
            CompareBean compareBean = new CompareBean();
            compareBean.setName("feeName");
            compareBean.setValue(formalObj.getFeeName());
            compareBeans.add(compareBean);
        }
        if (!tmpObj.getFeeScene().equals(formalObj.getFeeScene())){
            CompareBean compareBean = new CompareBean();
            compareBean.setName("feeScene");
            if ("0".equals(formalObj.getFeeScene())) {
                compareBean.setValue("单日交易累计金额计费");
            } else if ("1".equals(formalObj.getFeeScene())){
                compareBean.setValue("单笔交易计费");
            } else {
                compareBean.setValue(formalObj.getFeeScene());
            }
            compareBeans.add(compareBean);
        }
        String tmpfeeDesc = StringUtils.isNotBlank(tmpObj.getFeeDesc()) ? tmpObj.getFeeDesc() : "";
        String formalfeeDesc = StringUtils.isNotBlank(formalObj.getFeeDesc()) ? formalObj.getFeeDesc() : "";

        if (!tmpfeeDesc.equals(formalfeeDesc)){
            CompareBean compareBean = new CompareBean();
            compareBean.setName("feeDesc");
            compareBean.setValue(formalfeeDesc);
            compareBeans.add(compareBean);
        }

        return compareBeans;
    }

    //    @RequiresPermissions(value = {"费率管理:费率信息维护", "费率管理:费率信息审批"}, logical = Logical.OR)
    
    //@RequiresPermissions("商户管理:费率模板管理")
    @GetMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = false, dataType = "String")
    })
    public Map edits(@ModelAttribute("feeInfo") FeeInfo entity, Model model, HttpServletRequest request) throws RedpException {
        Map<String,Object> result= com.google.common.collect.Maps.newHashMap();
        List<FeeInfo> feeInfos = new ArrayList<>();
        String optFlag = request.getParameter("optFlag");
        String instId= request.getParameter("instId");
        List<CompareBean> compareBeans = new ArrayList<>();
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            String id = request.getParameter("id");
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常！");
            }
            // 审核：获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getById(id);
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据！");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }

            FeeInfo entity2 = JSON.parseObject(bizdata, FeeInfo.class);
            feeInfos.add(entity2);
            List<BizTmp> bizTmpList = bizTmpService.getBizTmpByMasterKey(user.getInstId(), tmp.getMasterKey());
            if (CollectionUtils.isNotEmpty(bizTmpList)){
                for (BizTmp bizTmp : bizTmpList){
                    String bizdataY = "";
                    if (null != bizTmp.getBizData1()) {
                        bizdataY += bizTmp.getBizData1();
                    }
                    if (null != bizTmp.getBizData2()) {
                        bizdataY += bizTmp.getBizData2();
                    }
                    if (null != bizTmp.getBizData3()) {
                        bizdataY += bizTmp.getBizData3();
                    }

                    FeeInfo entity3 = JSON.parseObject(bizdataY, FeeInfo.class);
                    feeInfos.add(entity3);
                }
            }

            if (Common.isBlank(feeInfos) || feeInfos.size() <= 0) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
            BeanUtils.copyProperties(feeInfos.get(0), entity);

            //临时表中操作为修改的话，比对差异数据
            if (BizOprEnum.OPR_UPDATE.getType().equals(tmp.getBizOpr())){
                List<FeeInfo> formalFeeInfos = feeInfoService.findcd(entity.getFeeCd(),entity.getInstId());
                compareBeans = combare(entity, formalFeeInfos.get(0));
            }
        } else if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            // 新增
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String crtOrgId = "";
            if(user.isAdmin()){
                if(StringUtils.isEmpty(instId)){
                    log.error("运营中心管理员新增数据必须先选择法人行！");
                    throw new RedpException("运营中心管理员新增数据必须先选择法人行！");
                }
            }else{
                instId=(instId==null?user.getInstId():instId);
            }
            entity.setInstId(instId);
            feeInfos = new ArrayList<>();
        } else {
            // 修改，注销，停用，启用，详情
            String feeCd = request.getParameter("feeCd");
            if(Common.isBlank(instId)){
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                instId = user.getInstId();
            }

            feeInfos = feeInfoService.findcd(feeCd,instId);
            if (null != feeInfos && feeInfos.size() > 0) {
                BeanUtils.copyProperties(feeInfos.get(0), entity);
            }
        }
        result.put("entity", entity);
        result.put("feeinfos", feeInfos);
        result.put("optFlag", optFlag);
        result.put("compareBeans",JSON.toJSONString(compareBeans));
        return result;
    }

    //    @RequiresPermissions(value = {"费率管理:费率信息维护", "费率管理:费率信息审批"}, logical = Logical.OR)
    
    //@RequiresPermissions("商户管理:费率模板管理")
    @PostMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = false, dataType = "String")
    })
    public OperationResult editSave(FeeInfoVO entity, Model model, HttpServletRequest request) throws RedpException {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        List<FeeInfo> feeInfoList = entity.getFeeInfoList();
        String optFlag = entity.getOptFlag();
        if (optFlag.equals("chk") || "stop".equals(optFlag) || "use".equals(optFlag) || optFlag.equals("upd")) {
            if (Common.isBlank(feeInfoList.get(0).getFeeCd())) {
                log.error("请求参数(FeeCd)异常!");
                return OperationResult.buildFailureResult("请求参数(FeeCd)异常!", result);
            }
        }

        String menuId;
        if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            menuId = String.valueOf(chkMenuId);
        } else {
            menuId = String.valueOf(oprMenuId);
        }
        OperationResult operationResult = feeInfoService.saveData(optFlag,menuId, oprMenuName, feeInfoList, request, webNextUrl);
        return operationResult;
    }

    //@RequiresPermissions("商户管理:费率模板管理")
    @PostMapping(value = "/delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键", required = true, dataType = "String")
    })
    public OperationResult delete(HttpServletRequest request) {
        String id = (request.getParameter("id") == null || request.getParameter("id") == "") ? "0" : request.getParameter("id");
        if (!id.equals("0")) {
            FeeInfo fee = feeInfoService.getById(id);
            if (fee.getImpStatus() != null && fee.getImpStatus() == BusinessContainer.impStatus_01) {
                feeInfoService.save(fee);
            } else {
                feeInfoService.getBaseMapper().deleteById(Long.valueOf(id));
            }
        }
        return OperationResult.buildSuccessResult();
    }

    /**
     * 分段信息-新增时调用
     */
    @ApiOperation(value = "分段信息-新增时调用")
    @GetMapping(value = "/stageInfo")
    public Map stageInfoShow(@ModelAttribute("feeInfo") FeeInfo entity, Model model, HttpServletRequest request) {
        Map<String,Object> result= com.google.common.collect.Maps.newHashMap();
        String feeName = request.getParameter("feeName");
        String feeDesc = request.getParameter("feeDesc");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String optFlag = request.getParameter("optFlag");
        String feeCd = request.getParameter("feeCd");
        String endValue = request.getParameter("endValue");
        String index = request.getParameter("index");
        result.put("feeCd", feeCd);
        entity.setFeeCd(feeCd);
        entity.setFeeDesc(feeDesc);
        entity.setStartDate(startDate);
        entity.setEndDate(endDate);
        entity.setFeeIntvMethod("");
        entity.setPCalType("");
        entity.setPStartValue("0");
        entity.setPEndValue("99999999999999.99");
        result.put("feeName", feeName);
        result.put("feeDesc", feeDesc);
        result.put("startDate", startDate);
        result.put("endDate", endDate);
        result.put("optFlag", optFlag);
        result.put("pStartValue", 0);
        result.put("pEndValue", "99999999999999.99");
        result.put("status", BusinessContainer.status_00);
        result.put("impStatus", BusinessContainer.impStatus_00);
        result.put("endValue", endValue);
        result.put("index", index);
        result.put("entity", entity);
        result.put("entity", entity);
        return result;
    }

    /**
     * 分段信息-修改时调用
     */
    @ApiOperation(value = "分段信息-修改时调用")
    @GetMapping(value = "/stageInfoEdit")
    public Map stageInfoEditShow(@ModelAttribute("feeInfo") FeeInfo entity, Model model, HttpServletRequest request) {
        Map<String,Object> result= com.google.common.collect.Maps.newHashMap();
        String optFlag = request.getParameter("optFlag");
        String pStartValue = request.getParameter("pStartValue");
        String pEndValue = request.getParameter("pEndValue");
        String index = request.getParameter("index");

        result.put("optFlag", optFlag);
        result.put("pStartValue", pStartValue);
        result.put("pEndValue", pEndValue);
        result.put("index", index);
        result.put("entity", entity);
        result.put("entity", entity);
        return result;
    }

    /**
     * 分段信息-删除时调用
     */
    @ApiOperation(value = "分段信息-删除时调用")
    @GetMapping(value = "/stageInfodelete")
    public void stageInfodelete(@ModelAttribute("feeInfo") FeeInfo entity, Model model, HttpServletRequest request) {
        feeInfoService.getBaseMapper().deleteById(entity.getId());
    }
    

    /**
     * 批量导入费率信息模板下载
     */
    @ApiOperation(value = "批量导入费率信息模板下载")
    @GetMapping(value = "/getExcel")
    public void getExcel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String file = "费率信息批量导入模版.xls";
        ExcelDownload.getExcel(request, response, file);
    }

    /**
     * 批量导入费率信息上传
     *
     * @param excelFile
     * @param request
     * @param response
     * @throws Exception
     */
    @PostMapping(value = "/upload")
    @ApiOperation(value = "批量导入费率信息上传")
    @ApiImplicitParams({
           @ApiImplicitParam(paramType = "query", name = "upload", value = "上传的文件", required = true, dataType = "String")
    })
    public void getDataFromExcel(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "excelFile", required = false) MultipartFile excelFile) throws Exception {
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = UUID.randomUUID().toString() + "_" + excelFile.getOriginalFilename();
        String filePath = path + File.separator + "temp" + File.separator + fileName;
        // 增加一层临时目录
        File targetFile = new File(path + File.separator + "temp" + File.separator, fileName);
        // 如果目录不存在，创建目录
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 将上传文件保存到临时目录
        try {
            excelFile.transferTo(targetFile);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        // 判断是否为excel类型文件
        if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
            log.error("文件不是excel类型");
            return;
        }
        // 获取一个绝对地址的流
        FileInputStream fis = new FileInputStream(filePath);
        HSSFWorkbook workbook = null;
        try {
            // 支持2003版本的excel，用[.xls结尾]的工作簿
            workbook = new HSSFWorkbook(fis);
        } catch (Exception e) {
            log.error("获取当前工作簿报错", e);
        } finally {
            fis.close();
        }
        // 获取工作表
        HSSFSheet sheet = workbook.getSheetAt(0);
        // 获取工作表行数
        int realRows = sheet.getLastRowNum();
        int index = 0;
        // 遍历行数据（不含模板标题）
        for (int i = 2; i < realRows - 1; i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                log.info("第" + (i - 1) + "行数据为空");
                continue;
            }
            // 保存当前行数据
            try {
                feeInfoService.saveFeeInfos(row);
                index++;
                log.error("批量导入费率信息_" + (i - 1) + "成功");
            } catch (Exception e) {
                log.error("批量导入费率信息_" + (i - 1) + "报错", e);
            }
        }
        response.getWriter().print("导入商户信息 [ " + index + " ] 条，成功 [ " + index + " ] 条");
        log.info("导入Excel数据总共：" + realRows + "条，成功" + index + "条");

        // 删除临时目录
        if (targetFile.isDirectory()) {
            log.info(targetFile + "是文件夹，删除临时文件夹下的所有文件");
            File[] files = targetFile.listFiles();
            for (File file : files) {
                file.delete();
            }
        } else {
            log.info(targetFile + "不是文件夹，直接删除");
            targetFile.delete();
        }
    }


    //	===============================================================================

    /**
     * 根据费率代码查询费率模板
     *
     * @param request
     * @return
     */
    
    //@RequiresPermissions("产品管理:支付通道管理")
    @PostMapping(value = "/editDstChnl")
    @ApiOperation(value = "根据费率代码查询费率模板")
//    public OperationResult editDstChnl(@RequestBody FeeInfo entity,String dstChannelId, Model model, HttpServletRequest request) {
    @ApiImplicitParam(paramType = "query", name = "feeCd", value = "费率代码", required = true, dataType = "String")
    public OperationResult editDstChnl(@ModelAttribute("feeInfo") FeeInfo entity, Model model, HttpServletRequest request)throws RedpException {
        String feeCd = entity.getFeeCd();
        String instId = entity.getInstId();
//        String feeCd = request.getParameter("feeCd");
//        String instId = request.getParameter("instId");
//        String dstChannelId = request.getParameter("dstChannelId");

        if(Common.isBlank(instId)){
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            instId=user.getInstId();
        }
        List<FeeInfo> feeList = feeInfoService.findcd(feeCd,instId);
        if (CollectionUtils.isEmpty(feeList)) {
            return OperationResult.buildFailureResult("没有找到费率数据！");
        }
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        result.put("feeList",feeList);
        result.put("feeCd",feeCd);
        result.put("instId",instId);
        result.put("dstChannelId",request.getParameter("dstChannelId"));
        result.put("optFlag",request.getParameter("optFlag"));
        return OperationResult.buildSuccessResult("操作处理成功",result);
    }

    /**
     * 根据费率代码查询费率模板
     *
     * @param request
     * @return
     */
    //@RequiresPermissions("产品管理:支付通道管理")
    @GetMapping(value = "/getFeeByDstChnl")
    @ApiImplicitParam(paramType = "query", name = "feeCd", value = "费率代码", required = true, dataType = "String")
    public OperationResult getFeeByDstChnl(Model model, HttpServletRequest request)throws RedpException {
        String feeCd = request.getParameter("feeCd");
        String instId = request.getParameter("instId");

        if(Common.isBlank(instId)){
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            instId=user.getInstId();
        }
        List<FeeInfo> feeList = feeInfoService.findcd(feeCd,instId);
        if (CollectionUtils.isEmpty(feeList)) {
            return OperationResult.buildFailureResult("没有找到费率数据！");
        }
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        result.put("feeList",feeList);
        return OperationResult.buildSuccessResult("操作处理成功",result);
    }

    @GetMapping(value = "/feeCdSelect2List")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "q", value = "参数", required = true, dataType = "String")
    })
    public Map feeCdSelect2List(QueryRequest request,String q) {
        return feeInfoService.feeInfoRSelect2List(request,q);
    }

}
